package com.learing.handler.realChat;

import com.learing.codec.protocol.LoginRequestPacket;
import com.learing.response.LoginResponsePacket;
import com.learing.session.Session;
import com.learing.utils.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;
import java.util.UUID;

/**
 * 登录处理器
 */
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket loginRequestPacket) {
        ctx.channel().writeAndFlush(login(loginRequestPacket, ctx));
    }

    /**
     * 随机产生用户ID
     *
     * @return
     */
    private static String randomUserId() {
        return UUID.randomUUID().toString().split("-")[0];
    }


    private LoginResponsePacket login(LoginRequestPacket loginRequestPacket, ChannelHandlerContext ctx) {

        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        loginResponsePacket.setVersion(loginRequestPacket.getVersion());
        loginResponsePacket.setUserName(loginRequestPacket.getUsername());
        if (valid(loginRequestPacket)) {
            System.err.println("标记为已经登录");
            String userId = randomUserId();
            loginResponsePacket.setUserId(userId);
            SessionUtil.bindSession(new Session(userId, loginRequestPacket.getUsername()), ctx.channel());
            loginResponsePacket.setSuccess(true);
            System.out.println(loginRequestPacket.getUsername()+"["+userId+"]于"+new Date() + ": 登录成功!");
        } else {
            loginResponsePacket.setReason("账号密码校验失败");
            loginResponsePacket.setSuccess(false);
            System.out.println(new Date() + ": 登录失败!");
        }
        return loginResponsePacket;
    }

    private boolean valid(LoginRequestPacket loginRequestPacket) {
        System.err.println(loginRequestPacket);
        return true;
    }

    /**
     * 用户断线之后取消绑定
     * @param ctx
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        SessionUtil.unBindSession(ctx.channel());
    }
}